<script setup lang="ts">
import { ref, reactive, watch, nextTick, onBeforeUnmount } from "vue";
import {
  AttrInfo,
  AttrInfoListResp,
  AttrValueInfo,
} from "@/api/product/attr/type";
import {
  getAttrList,
  saveOrUpdateAttr,
  getAttrDetail,
  deleteAttr,
} from "@/api/product/attr";
import categoryConfigStore from "@/store/modules/categoryConfig";
import { ElMessage, ElMessageBox } from "element-plus";
let categoryConfig = categoryConfigStore();
//表格数据
const tableData = ref<AttrInfo[]>([]);
//表单数据
const formData = reactive<AttrInfo>({
  attrName: "",
  attrValueList: [],
  categoryId: undefined,
  categoryLevel: 3,
});
//卡片组件内容切换
const scene = ref<number>(1);
//编辑模式或查看模式
const isLock = ref<boolean[]>([]);
//准备一个数组，存放多个组建实例
let inputCompArr = ref<any>([]);
//获取表格数据
const getAttrListData = async () => {
  const { category1Id, category2Id, category3Id } = categoryConfig;
  const res: AttrInfoListResp = await getAttrList(
    category1Id,
    category2Id,
    category3Id,
  );
  if (res.code === 200) {
    tableData.value = res.data;
  }
};
//监听三级分类id
watch(
  () => categoryConfig.category3Id,
  () => {
    tableData.value = [];
    if (!categoryConfig.category3Id) {
      return;
    }
    getAttrListData();
  },
);
//添加属性值
const addAttr = () => {
  //清空数据
  Object.assign(formData, {
    attrName: "",
    attrValueList: [],
    categoryId: categoryConfig.category3Id,
    categoryLevel: 3,
  });
  isLock.value = [];
  scene.value = 0;
  categoryConfig.isDisabled = true;
};
//编辑属性
const editAttr = async (row: AttrInfo) => {
  const res: any = await getAttrDetail(row.id);
  if (res.code != 200) {
    ElMessage.error("获取属性详情失败");
    return;
  }
  formData.attrValueList = res.data;
  for (let index = 0; index < res.data.length; index++) {
    isLock.value.push(true);
  }
  formData.attrName = row.attrName;
  formData.id = row.id;
  scene.value = 0;
  categoryConfig.isDisabled = true;
};
//保存
const saveAttr = async () => {
  if (categoryConfig.category3Id === undefined) {
    return ElMessage.error("请选择三级分类");
  }
  const res: any = await saveOrUpdateAttr(formData);
  if (res.code === 200) {
    ElMessage.success("保存成功");
    getAttrListData();
    scene.value = 1;
  } else {
    ElMessage.error("保存失败");
  }
};
//删除
const delAttr = (row: AttrInfo) => {
  const attrName = row.attrName;
  ElMessageBox.confirm("确定删除“" + attrName + "”属性?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res: any = await deleteAttr(row.id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getAttrListData();
      } else {
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {});
};
//取消
const cancel = () => {
  scene.value = 1;
  categoryConfig.isDisabled = false;
};
//添加属性值
const addAttrValue = () => {
  formData.attrValueList.push({
    valueName: "",
  });
  isLock.value.push(false);
  nextTick(() => {
    if (inputCompArr.value.length > 0) {
      inputCompArr.value[inputCompArr.value.length - 1].focus();
    }
  });
};
//查看模式与编辑模式切换
const toLock = (row: AttrValueInfo, $index: number) => {
  if (!row.valueName || row.valueName.trim() === "") {
    //为空直接删除
    delAttrValue($index);
    return;
  }
  if (formData.attrValueList.length != 0) {
    const repeat = formData.attrValueList.find(
      (item: any) => item.valueName == row.valueName && item != row,
    );
    if (repeat) {
      delAttrValue($index);
      ElMessage.error("属性值不能重复");
      return;
    }
  }
  isLock.value[$index] = true;
};
const toEdit = ($index: number) => {
  isLock.value[$index] = false;
  //使input获取焦点
  nextTick(() => {
    inputCompArr.value[$index].focus();
  });
};
//删除属性值
const delAttrValue = (index: number) => {
  formData.attrValueList.splice(index, 1);
  isLock.value.splice(index, 1);
};
//路由组件销毁的时候
onBeforeUnmount(() => {
  categoryConfig.$reset();
});
</script>

<template>
  <div>
    <Category />
    <el-card style="margin: 20px 0">
      <div v-if="scene === 1">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          @click="addAttr"
          :disabled="categoryConfig.category3Id ? false : true"
          >添加属性</el-button
        >
        <el-table :data="tableData" style="width: 100%; margin-top: 10px">
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="attrName" label="属性名称" width="180" />
          <el-table-column prop="attrValueList" label="属性值列表">
            <template #default="{ row }">
              <el-tag
                type="success"
                v-for="item in row.attrValueList"
                :key="item.id"
                >{{ item.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="editAttr(row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="delAttr(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              v-model="formData.attrName"
              placeholder="请您输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="!formData.attrName"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button type="default" size="default" @click="cancel"
          >取消</el-button
        >
        <el-table border style="margin: 10px 0" :data="formData.attrValueList">
          <el-table-column label="序号" type="index" width="80px" />
          <el-table-column label="属性值">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc: any) => (inputCompArr[$index] = vc)"
                v-if="!isLock[$index]"
                v-model="row.valueName"
                prop="valueName"
                placeholder="请您输入属性值"
                @blur="toLock(row, $index)"
              ></el-input>
              <div v-else @click="toEdit($index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="属性值操作">
            <template #="{ row, $index }">
              <el-popconfirm
                :title="`确定删除${row.valueName}吗？`"
                @confirm="delAttrValue($index)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          @click="saveAttr"
          :disabled="formData.attrValueList.length === 0"
          >保存</el-button
        >
        <el-button type="default" size="default" @click="cancel"
          >取消</el-button
        >
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
